function TaSum = my_binsum(Data,Index,Edge,opt)
% Table = my_binsum(Data,Index,Edge)
% ---------------------------------
% plot binned average, bin divided by Index
% Input:
% 	Data: double 
% 	Index: grouped metrics
% 	Edge: the value of bin range, similar to hist
% 	opt:
% 		"UncentaintyMethod": string,
% 			"std": use standard deviation as uncertainty
% 			"bootstrap": use standard bootstrap method to get uncertainty
% Output:
% 	figure of binned average
% 	Table of each binned group, with mean and uncertainty
%
% Author:
% 	Sid Chen
% Date: 2022/08/24
% Log: 
% 	2022/08/24 created
%
	arguments
		Data
		Index
		Edge
		opt.UncentaintyMethod  = "bootstrap"
	end

	N_bin = numel(Edge) -1;
	% TaSum is the table to hold information of each bin
	TaSum = table('Size',[N_bin,4],...
		'VariableTypes',{'string','double','double','double'},...
		'VariableNames',{'bin_range','mean','lowerbound','upperbound'});

	for ii = 1:N_bin
		lowerbound = Edge(ii);
		upperbound = Edge(ii+1);
		data_in_range = Data(Index >= lowerbound & Index < upperbound);
		TaSum{ii,1} = sprintf("[ %.1f, %.1f )",lowerbound,upperbound);
		TaSum{ii,2:4} = sub_getMeanAndErrorbar(data_in_range,opt.UncentaintyMethod);
	end

	X = 1:N_bin;
	hold on
	bar(X,TaSum{:,2});
	errorbar(X,TaSum{:,2},TaSum{:,3},TaSum{:,4},'k');
	xticks(X);
	xticklabels(TaSum{:,1});
	hold off
end

function out = sub_getMeanAndErrorbar(Data,Method)
	if Method == "std"
		Mean = mean(Data,'all');
		Std = std(Data,1,'all');
		out = [Mean, -Std, + Std];
	elseif Method == "bootstrap"
		sample_bs = bootstrp(500,@mean,Data);

		bias = mean(sample_bs) - mean(Data);
		Mean = mean(Data) - bias;

		Std = std(sample_bs,1,'all');
		out = [Mean, -1.96*Std, 1.96*Std];
	end
end

